<template>
  <section class="page-content">
    <el-tabs value="basic" @tab-click="handleClick" type="border-card">
      <el-tab-pane label="基本信息" name="basic">
        <el-form size="medium" :model="formData" :rules="rules" ref="formData" label-width="100px" class="form-goods-basic">
          <el-form-item label="课程序号" prop="order">
            <el-input type="number" v-model.number="formData.order"></el-input>
          </el-form-item>
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>
          <el-form-item label="单节售价" prop="price" >
            <el-input v-model="formData.price"></el-input>
          </el-form-item>
          <el-form-item label="赠送积分" prop="give_integral">
            <el-input type="number" v-model="formData.give_integral"></el-input>
          </el-form-item>
          <el-form-item label="兑换积分" prop="exchange_integral">
            <el-input type="number" v-model="formData.exchange_integral"></el-input>
          </el-form-item>
          <el-form-item label="一级提成" prop="bonus_ratio_1">
            <el-input v-model="formData.bonus_ratio_1"></el-input>
          </el-form-item>
          <el-form-item label="二级提成" prop="bonus_ratio_2">
            <el-input v-model="formData.bonus_ratio_2"></el-input>
          </el-form-item>
          <el-form-item label="课程属性">
            <el-radio v-model.number="formData.type" :label="1">视频</el-radio>
            <el-radio v-model.number="formData.type" :label="2">音频</el-radio>
            <el-radio v-model.number="formData.type" :label="3">图文</el-radio>
          </el-form-item>
          <el-form-item label="上传视频" v-if="formData.type === 1">
            <el-upload
              accept="video/mp4"
              :data="{folder: 'video'}"
              :action="$serverUrl + '/api/upload/file'"
              :on-remove="handleRemoveVideo"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              :on-success="uploadVideoSuccess"
              :on-error="uploadError"
              :limit="1"
              :file-list="videoList">
              <el-button size="small" type="default">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传音频" v-if="formData.type === 2">
            <el-upload
              accept="audio/mp3"
              file="file"
              :data="{folder: 'audio'}"
              :action="$serverUrl + '/api/upload/file'"
              :on-remove="handleRemoveAudio"
              :before-upload="beforeUpload"
              :on-exceed="handleExceed"
              :on-success="uploadAudioSuccess"
              :on-error="uploadError"
              :limit="1"
              :file-list="audioList">
              <el-button size="small" type="default">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传mp3文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="图文内容" v-if="formData.type === 3" style="width: 800px;">
            <tinymce :height="500" v-model="formData.body"></tinymce>
          </el-form-item>
          <el-form-item>
            <el-button :loading="loading" type="primary" @click="submitCourse('formData')">保存</el-button>
            <el-button @click="resetForm('formData')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </section>
</template>

<script>
  import Tinymce from '@/components/tinymce/Editor'
  export default {
    name: 'course',
    data () {
      return {
        loading: false,
        visible: false,
        limitSize: 100,
        dialogImageUrl: '',
        dialogVisible: false,
        teachers: [],
        tempData: {
          id: null,
          name: '',
          course_id: 0,
          type: 1,
          thumb: '',
          video_path: '',
          audio_path: '',
          price: '',
          give_integral: 0,
          exchange_integral: 0,
          order: null,
          bonus_ratio_1: 0.00,
          bonus_ratio_2: 0.00,
          body: ''
        },
        formData: {},
        rules: {
          name: [
            { required: true, message: '请输入课程名称', trigger: 'blur' },
            { min: 1, max: 250, message: '长度在1到250个字符', trigger: 'blur' }
          ],
          category_id: [
            { required: true, type: 'number', message: '请选择课程分类', trigger: 'change' }
          ],
          teacher_id: [
            { required: true, type: 'number', message: '请选择老师', trigger: 'change' }
          ],
          thumb: [
            { required: true, message: '请上传缩略图', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          order: [
            { type: 'number', required: true, message: '请填写排序', trigger: 'blur' }
          ],
          bonus_ratio_1: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ],
          bonus_ratio_2: [
            { required: true, message: '该字段必填', trigger: 'blur' }
          ]
        }
      }
    },
    components: { Tinymce },
    methods: {
      handleExceed () {
        this.$message.error('只能上传1个文件')
      },
      handleRemoveVideo (file, fileList) {
        console.log(file, fileList)
        this.formData.video_path = null
      },
      uploadVideoSuccess (response, file, fileLis) {
        this.formData.video_path = response
      },
      handleRemoveAudio (file, fileList) {
        console.log(file, fileList)
        this.formData.audio_path = null
      },
      uploadAudioSuccess (response, file, fileLis) {
        this.formData.audio_path = response
      },
      beforeUpload (file) {
        const sizeLimit = file.size / 1024 / 1024 < this.limitSize
        if (!sizeLimit) {
          this.$message.error('上传文件大小不能超过' + this.limitSize + 'MB!')
        }
        return sizeLimit
      },
      uploadError (error, file, fileList) {
        console.log(error)
        this.$message.error('上传失败')
      },
      handleClick (tab, event) {
        console.log(tab, event)
      },
      submitCourse (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this._createOrEditCourse()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      },
      _createOrEditCourse () {
        this.loading = true
        this.$http({
          method: this.isEdit ? 'put' : 'post',
          url: this.isEdit ? '/catalogs/' + this.formData.id : '/catalogs',
          data: this.formData
        }).then((response) => {
          this.loading = false
          this.$message.success('保存成功')
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _resetCourse () {
        if (!this.isEdit) {
          this.tempData.course_id = this.$route.params.id
        }
        this.formData = Object.assign({}, this.tempData)
      },
      _getData () {
        this.$http.get('/catalogs/' + this.$route.params.id + '/edit').then((response) => {
          this.formData = response.data
          this.$refs.goodsAttr.getAttrs(response.data.type_id, response.data.id)
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    computed: {
      isEdit () {
        return this.$route.meta.isEdit
      },
      audioList () {
        if (this.isEdit && this.formData.audio_path) {
          return [{name: this.formData.audio_path}]
        }
        return []
      },
      videoList () {
        if (this.isEdit && this.formData.video_path) {
          return [{name: this.formData.video_path}]
        }
        return []
      }
    },
    watch: {
      '$route' (to, from) {
        if (!to.meta.isEdit) {
          this._resetCourse()
        } else {
          this._getData()
        }
      }
    },
    mounted () {
      this._resetCourse()
      if (this.isEdit) {
        this._getData()
      }
    }
  }
</script>
<style scoped lang="scss">
  .form-goods-basic {
    width: 700px;
    .el-select {
      width: 100%;
    }
  }
  .form-goods-body {
    margin-top: 20px;
  }
  .thumb-uploader, .thumb-uploader-icon, .thumb-img{
    width: 200px;
    height: 200px;
  }
  .thumb-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    &:hover {
      border-color: #20a0ff;
    }
    .thumb-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      line-height: 200px;
      text-align: center;
      &:hover {
        color: #20a0ff;
      }
    }
  }
  .dialog {
      .el-input {
        width: 100%;
      }
      .el-select {
        width: 100%;
      }
    } 
</style>